package com.zzy.util.velocity;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;
import java.util.*;

// https://vimsky.com/examples/detail/java-method-org.apache.velocity.app.VelocityEngine.getTemplate.html

public class TestVelocity {
    public static void main(String[] args) {
        test();
    }


    public static void test(){


        VelocityEngine velocityEngine = new VelocityEngine();
//        Properties properties = new Properties();
//        properties.setProperty("resource.loader", "class");
//        properties.setProperty("class.resource.loader.class",  "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//        velocityEngine.init(properties);
        velocityEngine.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName());
        //String templateSrc = "D:\\newspace\\springclouddemo\\zzy-util\\src\\main\\java\\com\\zzy\\util\\velocity\\template.html";
        String templateSrc = "velocityTemplate/template.html";
        Template template = velocityEngine.getTemplate(templateSrc,"utf-8");
        VelocityContext velocityContext = new VelocityContext();
        setData(velocityContext);
        StringWriter stringWriter = new StringWriter();
        template.merge(velocityContext, stringWriter);
        String str = stringWriter.toString();
        System.out.println( str );
    }
    // <!-- #set、#if 、#else、#end、#foreach、#end、#iinclude、#parse、#macro -->
    // #parse("/blog/top.html")或#include("/blog/top.html")
    public static void setData(VelocityContext velocityContext){
        velocityContext.put("userName","张无忌");

        velocityContext.put("createTime",new Date());

        velocityContext.put("subStr","2024-03-27 10:49:43");

        velocityContext.put("num1","1");
        velocityContext.put("num2","2");

        Map map = new HashMap();
        map.put("title","这里是标题");
        velocityContext.put("data",map);

        List<Map<String,Object>> list = new ArrayList<>();
        for(int i =0 ; i< 5; i++){
            Map<String,Object> map1 = new HashMap<>();
            map1.put("name","名字->"+ ( i+1));
            Integer sex = i/2==0 ? 0 : 1 ;
            map1.put("sex", sex );
            map1.put("id", (100+i) );
            list.add(map1);
        }
        velocityContext.put("list",list);

    }
}
